import {ResolvedFn, RejectedFn} from "@/types";
import index from "@/store";

interface Interceptor<T> {
    resolved: ResolvedFn<T>
    rejected?: RejectedFn
}

export default class InterceptorManager<T> {
    private interceptors: Array<Interceptor<T> | null>

    constructor() {
        this.interceptors = []
    }

    use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number {
        this.interceptors.push({
            resolved,
            rejected
        })
        return this.interceptors.length - 1
    }

    /**
     * 遍历拦截器,传入inter去fn函数执行
     * @param fn 传入Interceptor<T>类型
     */
    forEach(fn:(interceptor:Interceptor<T>)=>void):void{
        this.interceptors.forEach(interceptor=>{
            if (interceptor!==null){
                fn(interceptor);
            }
        })
    }

    eject(id: number): void {
        if (this.interceptors[id]) {
            //interceptor支持泛型,不支持null,所以需要声明联合类型
            this.interceptors[id] = null
        }
    }
}